/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.easyOrder.core.comm;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
//import ma.glasnost.orika.impl.generator.EclipseJdtCompilerStrategy;

/**
 * 简单封装orika, 实现深度转换Bean<->Bean的Mapper.
 */
public class BeanMapper {

    private static MapperFacade mapper = null;

    static {
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
//		MapperFactory mapperFactory = 
//			    new DefaultMapperFactory.Builder()
//			            .compilerStrategy(new EclipseJdtCompilerStrategy())
//			            .build();
        mapper = mapperFactory.getMapperFacade();

    }

    /**
     * 基于Dozer转换对象的类型.
     */
    public static <S, D> D map(S source, Class<D> destinationClass) {
        return mapper.map(source, destinationClass);
    }

    /**
     * 基于Dozer转换Collection中对象的类型.
     */
    public static <S, D> List<D> mapList(Iterable<S> sourceList, Class<D> destinationClass) {
        return mapper.mapAsList(sourceList, destinationClass);
    }

    /**
     * 集合转map
     *
     * @param sourceList 集合
     * @param IMapKey    getkey方法
     * @param <S>        集合对像类型
     * @param <D>        key类型
     * @return
     */
    public static <S, D> Map<S, D> toMap(Iterable<D> sourceList, Function<D, S> IMapKey) {
        Map<S, D> result = Maps.newHashMap();
        if (sourceList == null) {
            return result;
        }
        for (D d : sourceList) {
            result.put(IMapKey.apply(d), d);
        }
        return result;
    }

    /**
     * 集合转map
     *
     * @param sourceList 集合
     * @param IMapKey    getkey方法
     * @param <S>        集合对像类型
     * @param <D>        key类型
     * @return
     */
    public static <S, D> Map<S, List<D>> toMapList(Iterable<D> sourceList, Function<D, S> IMapKey) {
        Map<S, List<D>> result = Maps.newHashMap();
        if (sourceList == null) {
            return result;
        }
        for (D d : sourceList) {
            S key = IMapKey.apply(d);
            if (result.containsKey(key)) {
                List<D> list = result.get(key);
                list.add(d);
            } else {
                List<D> list = Lists.newArrayList();
                list.add(d);
                result.put(key, list);
            }
        }
        return result;
    }
}